layui.define(['layer', 'jquery'], function (exports) {
    var layer = layui.layer, $ = layui.$;
    /*
     * 参数说明
     * url:后台请求路径
     * post:请求方法
     * obj：请求参数
     * asyncType:是否同步 默认异步处理 ,因为我们返回值的问题我们将默认设置true
     */
    var cstmodules = {
        callBackMethod:function (url,post,dataobj) {
            var data1=null;
            $.ajax({
                url:url,
                type:post,
                contentType: "application/json; charset=utf-8",
                data:JSON.stringify(dataobj),
                Caches:false,
                async:false,
                dataType:"json",
                success:function (data) {
                    data1=data;
                },
                error:function (data) {
                    console.log(JSON.stringify(data));
                    layer.msg("执行事务失败,请联系管理员！");
                    return null;
                }
            });
            return data1;
        },
        /*
           将from表单转换成json对象
         */
        serializeJsonObj:function(fromid)
        {
            var o = {};
            var a = $("#"+fromid).serializeArray();
            console.log(a);
            $.each(a, function() {
                if (o[this.name]) {
                    if (!o[this.name].push) {
                        o[this.name] = [o[this.name]];
                    }
                    o[this.name].push(this.value || '');
                } else {
                    o[this.name] = this.value || '';
                }
            });
            return o;
        },
        initSelectContent: function (form, selectId, data, wakeText, selValue) {
            $("#" + selectId).empty();
            var selValue = selValue || null;
            var wakeText = wakeText || null;
            var tempValue = null;
            if (wakeText != null) {
                tempValue = "<option value=''>" + wakeText + "</option>";
                $("#" + selectId).append(tempValue);
            }

            if (data != null) {
                data.forEach(function (vals, index, arr) {
                    if (selValue == vals.dictvalue) {
                        console.log(vals.dictid);
                        tempValue = "<option value=" + vals.id + " selected>" + vals.dictvalue + "</option>";
                    } else {
                        tempValue = "<option value=" + vals.id + ">" + vals.dictvalue + "</option>";
                    }
                    $("#" + selectId).append(tempValue);
                });
            }
            form.render('select');
            return false;
        },

        initSelectView: function (form, url, selectId, groupid, wakeText, selValue) {
            console.log(groupid)
            var param = {
                groupid: groupid
            };
          //  var data = this.callBackMethod("/sys/getSelectList", "post", param, null);
            var data = this.callBackMethod(url, "post", param, null);

            if (data.code == 1) {
                this.initSelectContent(form, selectId, data.listObj, wakeText, selValue);
            }
        },
        initTableSelect: function (form, selectId, url, wakeText, selValue) {
            var data = this.callBackMethod(url, "post", null, null);
            if (data != null && data.code == 1) {
                this.initSelectContent(form, selectId, data.listObj, wakeText, selValue);
            }

        },
        initTableMethodH: function (table, id, url, param, cols, height) {
            var data = this.callBackMethod(url, "post", param, null);
            var obj = data||null;
            var loading=layer.msg('数据加载中...');
            table.render({
                elem: '#' + id
                , data: obj
                ,toolbar: '#toolbarDemo' //开启头部工具栏，并为其绑定左侧模板
                ,defaultToolbar: ['filter', 'exports', 'print']
                , limit: 10
                , limits: [10, 20, 50, 100, 200, 500]
                , page: {groups: 3, prev: '上一页', next: '下一页'}
                , loading: true
                , height:this.initTablHeight(height)
                , align: 'center'
                /* ,size: 'sm' //小尺寸的表格*/
                , cols: cols
            });
            return obj;
        },
        initPageTableMethod: function (table, id, url, clos,toolbar, param, limit, limits, height) {
            var loading=layer.msg('数据加载中...');
            table.render({
                elem: '#' + id
                , height:this.initTablHeight(height)
                , url: url, where: param || null  //数据接口
                , request: {
                    pageName: 'curr' //页码的参数名称，默认：page
                    , limitName: 'nums' //每页数据量的参数名，默认：limit
                }
                , method: 'get'
                , loading: true
                , limit: limit || 10
                , limits: limits || [10, 20, 50, 100]
                , page: {groups: 3, prev: '上一页', next: '下一页'}
                , cols: clos
                ,toolbar: toolbar||null
                ,done:function (res, curr, count) {
                    if(typeof(res.info)!= 'undefined' &&  res.info=="999"){
                        window.location="/";
                    }else{
                        layer.closeAll('dialog');
                    }
                }
            })
        },
        //导出EXCL的公用方法
        exclExportlMthod: function (type, sheetName, columnIt, filedName, fileName,btnAuth,queryParam) {
            var param = {
                type: type,
                sheetName: sheetName,
                columnIt: columnIt,
                filedName: filedName,
                fileName: fileName,
                btn_authid:btnAuth,
                queryParam:queryParam
            };
            var data = this.callBackMethod("/plugs/exclExport", "POST", param, false);
            if (data.state == 0) {
                window.open("/plugs/downFileMethod?fileName=" + data.allUrl + "&flag=1");
            } else {
                if(typeof(data.errInfo)!= 'undefined' && data.errInfo!="")
                    layer.msg(data.errInfo);
                return;
            }
        },
        /* excl 批量导入的前台功用方法
         * 2016年1月6日17:37:14
         * 苏辉
         */
        exclImportMethod: function (upload, id, url, params) {
            upload.render({
                elem: '#' + id
                , url: url + "?" + $.param(params)
                , method: 'post'
                , accept: 'file'
                , exts: 'xls|csv|xlsx'
                , size: 1024 * 10
                , done: function (data) {
                    layer.msg(data.info, function () {
                        parent.layer.closeAll();
                    });
                }
            });
        },
        ImageUploadMethod: function (upload, id, url,recoveId,saveId,viewId) {
            upload.render({
                elem: '#'+id
                , url: '/plugs/uploadImageMethod/'
                , method: 'post'
                , accept: 'file'
                , exts: 'jpg|gif|png|jpeg|bmp'
                , size: 1024
                ,auto:false
                ,bindAction:'#'+saveId
                ,choose:function (obj) {
                    obj.preview(function(index, file, result){
                        $('#'+viewId).attr('src', result); //图片链接（base64）
                        $('#'+saveId).css("display",'inline')
                    });
                }
                , done: function (data) {
                    if(data!=null){
                        if(data.state=='ok'){
                            $("#"+recoveId).val(data.info);
                            $('#'+saveId).css("display",'none')
                        }else{
                            layer.msg(data.info);
                        }
                    }
                }
            });
        },
        setNumberText: function (str) {
            $(str).bind("keyup blur", function (e) {
                this.value = this.value.replace(/\D/g, '');
            });
        },
        initTablHeight: function (hegiht) {
            if(hegiht==null || hegiht==0){
                return 472;
            }else{
                var h = $(window).height();
                //多减去5px 319
                return (h-hegiht)<0?0:(h-hegiht)+"px";
            }
        },

    }
    exports('cstmodules', cstmodules);
});